package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ZYJ on 2021/6/3 16:03
 */
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    private ApUserMapper apUserMapper;

    /**
     * app用户登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验参数  要么有设备id 要么有手机号密码
        if (dto.getEquipmentId() == null &&
                (StringUtils.isBlank(dto.getPassword()) &&
                        StringUtils.isBlank(dto.getPassword()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //如果有手机号和密码 查询手机号是否存在  然后MD5加盐比对密码
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号不存在");
            }
            String password = dto.getPassword();
            String saltPassword = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            //颁发token
            if (!saltPassword.equals(apUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "密码不正确,请重新输入");
            }
            String token = AppJwtUtil.getToken(apUser.getId().longValue());

            //封装参数
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("token", token);
            apUser.setPassword("");
            apUser.setSalt("");  //敏感数据置空 或封装vo
            dataMap.put("user",apUser);

            return ResponseResult.okResult(dataMap);

        } else {
            //使用设备id登录 直接颁发token  0
            String token = AppJwtUtil.getToken(0L);
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("token", token);
            return ResponseResult.okResult(dataMap);
        }
    }
}
